package co.sanduche.teach.service;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class TasksDBHelper extends SQLiteOpenHelper {

	private static final String CREATE_TABLE = "CREATE TABLE tasks (_id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, state INTEGER, entityId INTEGER)";
	private static final String TASKS_DB_NAME = "tasks";
	private static final int TASKS_DB_VERSION = 1;
	private SQLiteDatabase db;

	public TasksDBHelper(Context context) {
		super(context, TASKS_DB_NAME, null, TASKS_DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_TABLE);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public void insertTask(Class<? extends TaskExecutor> t, long entityId) {
		SQLiteDatabase db = getDB();
		ContentValues values = new ContentValues();
		values.put("type", t.getCanonicalName());
		values.put("entityId", entityId);
		values.put("state", 0);
		db.insert("tasks", null, values);
	}

	public Task popPendingTask() {

		SQLiteDatabase db = getDB();
		Cursor res = db.rawQuery(
				"SELECT * FROM (SELECT * FROM tasks WHERE state = 0 ORDER BY _id) LIMIT 1",
				new String[] {});
		boolean hasNext = res.moveToFirst();
		if (hasNext) {
			long id = res.getLong(0);
			String type = res.getString(1);
			long state = res.getLong(2);
			long entityId = res.getLong(3);
			return new Task(id, type, state, entityId);
		}
		return null;
	}

	public void update(Task t) {
		SQLiteDatabase db = getDB();
		ContentValues values = new ContentValues();
		// values.put("type", t.getType());
		// values.put("entityId", entityId);

		values.put("state", t.getState());
		db.update("tasks", values, "_id=" + t.getId(), new String[0]);

	}

	private SQLiteDatabase getDB() {
		if (db == null)
			db = getWritableDatabase();
		return db;
	}

}
